<?php

class dokeywords {

    public function tasks() {
        $lock_key = "tasks_lock_time_dokeywords";
        $bool = mredis::get($lock_key);
        if (empty($bool)) {
            try {
                mredis::setnxe($lock_key, 1, 60 * 10);
                $this->toDo();
                mredis::del($lock_key);
            } catch (Exception $ex) {
                logging_run('任务处理出错：' . $ex->getMessage(), 'error', 'dokeyword_run');
                mredis::del($lock_key);
            }
        } else {
            logging_run('任务正在处理中', 'trace', 'dokeyword_run');
        }
    }

    public function toDo() {

        $keys = mredis::keys('dokeywords_*');
        if (!empty($keys)) {
            foreach ($keys as $kv) {
                $lcount = 0;
                $congCount = 0;
                $errorCount = 0;
                $kd = explode('dokeywords_', $kv);
                $yuming_id = end($kd);
                $table = $this->get_tables_words($yuming_id);
                for ($i = 0; $i <= 100; $i++) {
                    $data = mredis::rPop('dokeywords_' . $yuming_id);
                    if (!empty($data)) {
                        $data = json_decode($data, true);
                        foreach ($data as $key => $v) {
                            try {
                                $v = trim($v);
                                $count = db::getField("select count(*) from `{$table}` where title='$v'");
                                if ($count == 0) {
                                    db::query("insert into `{$table}` (title) values ('$v')");
                                    $lcount++;
                                } else {
                                    $congCount++;
                                    continue;
                                }
                            } catch (Exception $ex) {
                                $errorCount++;
                                continue;
                            }
                        }
                    }
                }
                logging_run('完成一次任务，成功：' . $lcount . '，重复：' . $congCount . '，错误：' . $errorCount, 'trace', 'dokeyword_run');
            }
        }
    }

    //得到关键词库表
    protected function get_tables_words($yuming_id) {
        $table = "words_{$yuming_id}";
        if (!db::table_exist($table)) {
            $table = "words";
        }
        return $table;
    }

}
